package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func postJson(rawUrl, method string, requestBody string, headers map[string]string, timeout time.Duration) (result string, err error) {
	if timeout <= 0 {
		timeout = 5
	}
	client := &http.Client{
		Timeout: timeout * time.Second,
	}
	var jsonStr = []byte(requestBody)
	// 提交请求
	request, err := http.NewRequest(method, rawUrl, bytes.NewBuffer(jsonStr)) // json
	if err != nil {
		return
	}
	// 增加header头信息
	for key, val := range headers {
		request.Header.Set(key, val)
	}
	request.Header.Set("content-type", "application/json")

	response, err := client.Do(request)
	if err != nil {
		return
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		return "", fmt.Errorf("get content failed status code is %d ", response.StatusCode)
	}
	res, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}
	return string(res), nil
}

func main() {
	key := "java"
	nextCursor := "0"
	requestBody := fmt.Sprintf(`{"key_word": "%s", "id_type": 0, "cursor": "%s", "limit": 20, "search_type": 0}`, key, nextCursor)
	rawUrl := "https://apinew.juejin.im/search_api/v1/search"
	header := map[string]string{
		"User-Agent":      "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0",
		"Accept":          "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
		"Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
		"Accept-Encoding": "gzip, deflate, br",
		"Referer":         "https://juejin.im/search?query=" + key,
		"Content-Type":    "application/json",
		"Origin":          "https://juejin.im",
		"Connection":      "keep-alive",
		"Cookie":          "Hm_lvt_93bbd335a208870aa1f296bcd6842e5e=1585649229,1587023263; gr_user_id=7ff105a2-c311-4b09-8e5c-863db5cd60e9; _ga=GA1.2.1122042631.1585649230; MONITOR_WEB_ID=2c1db46d-5304-448e-bc50-bf8468205920; _gid=GA1.2.922206982.1599204376; passport_auth_status=897f38c36d5cb93bb74a60a160e95ab4%2C; sid_guard=8484d7c1ac371660428a885a45eb3c65%7C1599207068%7C5184000%7CTue%2C+03-Nov-2020+08%3A11%3A08+GMT; uid_tt=0663d12bb072ab748608a59eabe192f3; uid_tt_ss=0663d12bb072ab748608a59eabe192f3; sid_tt=8484d7c1ac371660428a885a45eb3c65; sessionid=8484d7c1ac371660428a885a45eb3c65; sessionid_ss=8484d7c1ac371660428a885a45eb3c65",
		"TE":              "Trailers",
	}
	result, err := postJson(rawUrl, "POST", requestBody, header, 5)
	if err != nil {
		log.Fatal("postJson err: ", err)
	}

	fmt.Println(result)
}
